package com.example.demo.service.impl;

import com.example.demo.mapper.AnnouncementMapper;
import com.example.demo.pojo.Announcement;
import com.example.demo.pojo.PageBean;
import com.example.demo.service.AnnouncementService;
import com.example.demo.utils.ThreadLocalUtil;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


@Service
public class AnnouncementServiceImpl implements AnnouncementService {

    @Autowired
    private AnnouncementMapper announcementMapper;
    @Override
    public void add(Announcement announcement) {
        Map<String,Object> map = ThreadLocalUtil.get();
        int userid = (Integer) map.get("userid");
        announcement.setUserid(userid);
        announcementMapper.add(announcement);

    }

    @Override
    public List<Announcement> findAll() {
        return announcementMapper.findAll();
    }

    /**
     * 根据分页参数和类别ID查询公告列表，并返回分页信息。
     *
     * @param pageNum  当前页码
     * @param pageSize 每页显示的数量
     * @param categoryId 公告类别ID，用于过滤公告
     * @return 包含公告分页信息的PageBean对象
     */
    @Override
    public PageBean<Announcement> list(int pageNum, int pageSize, Integer categoryId){
        // 初始化PageBean对象，用于存放分页后的数据和分页信息
        PageBean<Announcement> pb = new PageBean<>();
        // 初始化分页插件，设置当前页码和每页显示的数量
        PageHelper.startPage(pageNum, pageSize);

        // 从线程本地存储中获取用户ID，用于过滤公告
        Map<String,Object> map = ThreadLocalUtil.get();
        int userid = (int) map.get("userid");

        // 根据用户ID和类别ID查询公告列表
        List<Announcement> as = announcementMapper.list(userid, categoryId);
        // 将查询结果转换为Page对象，以获取总记录数等分页信息
        Page<Announcement> p = (Page<Announcement>) as;

        // 将分页信息设置到PageBean中
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());

        // 返回包含公告分页信息的PageBean对象
        return pb;
    }

}
